package com.brother.realtime;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.geotools.filter.expression.ThisPropertyAccessorFactory;

import com.brother.model.AlarmType;
import com.brother.model.DataFlag;
import com.brother.model.Tracker;
import com.brother.realtime.cache.ParametersSetCache;
import com.brother.realtime.config.ActionType;
import com.brother.util.CommonProperties;

public class ComandReader {
	private SocketChannel socketChannel = null;

	private long lastRecievedTime = System.currentTimeMillis();

	private long lostSignalLimit = 20000; // The time-span for setting lost
											// signal.

	private String remoteAddr = "";
	private String IMEI = null;
	private String trackerId = null;

	private String protocol = null;

	public String getProtocol() {
		return protocol;
	}

	public void setProtocol(String protocol) {
		boolean first = this.protocol == null;
		this.protocol = protocol;
		if (protocol != null && protocol.equals(Tracker.PROTOCOL_TL201)
				&& first) {
			if (this.cmds.size() > 0) {
				for (int i = 0; i < cmds.size(); i++) {
					Command cmd = cmds.get(i);
					if (cmd instanceof DataCommand) {
						Date d = ((DataCommand) cmd).getDate();
						d.setHours(d.getHours() - 8); // TL201模型不加8
						((DataCommand) cmd).setDate(d);
					} else if (cmd instanceof MutilDataCommand) {
						MutilDataCommand md = (MutilDataCommand) cmd;
						List<DataCommand> coms = md.getCommands();
						for (DataCommand cmd2 : coms) {
							Date d = cmd2.getDate();
							d.setHours(d.getHours() - 8); // TL201模型不加8
							cmd2.setDate(d);
						}
					}

				}
			}
		}
	}

	public String getTrackerId() {
		return trackerId;
	}

	public void setTrackerId(String trackerId) {
		this.trackerId = trackerId;
	}

	public boolean isStopped() {
		return false;
	}

	public ComandReader(SocketChannel socket, String remoteAddr1) {
		this.remoteAddr = remoteAddr1;
		this.socketChannel = socket;
		this.lostSignalLimit = CommonProperties.getLostSignalTime();
	}

	private Logger log = Logger.getLogger(this.getClass());
	private List<Command> cmds = new ArrayList<Command>();

	public Command readOneCommand() {
		if (IMEI != null) { // it is the third party proctocal
			if (cmds.size() > 0) { // There is cmd left.
				return cmds.remove(0);
			}
		}
		ByteBuffer bf = ByteBuffer.allocate(1);
		StringBuffer sb = new StringBuffer();
		try {
			int read = -1;
			while ((read = socketChannel.read(bf)) != -1) {// This method is not
															// blocked.
				if (read == 0) {
					long time = System.currentTimeMillis();
					if (time - this.lastRecievedTime > this.lostSignalLimit) {
						return new LostSignalCommand();
					}
					return null;
				}
				char c = (char) bf.get(0);
				bf.clear();
				if (c == '!') {
					sb.delete(0, sb.length());
				}
				// #356896031498455,CMD-T,A,DATE:110107,TIME:061607,LAT:22.6474566N,LOT:114.0310116E,Speed:000.0,0-0-0-0-85-30,000#
				if (c == '#' && (sb.length() > 1)
						&& ((sb.charAt(0) != '!') && (sb.charAt(0) != '#'))) {
					sb.delete(0, sb.length());
				}
				// System.out.println(remoteAddr+" input char:" + c);
				sb.append(c);
				lastRecievedTime = System.currentTimeMillis();
				if (c == ';') {
					try {
						return parseCommand(sb.toString());
					} catch (Exception e) {
						log.error("parse command error! " + remoteAddr + ","
								+ this.IMEI + ",input:" + sb.toString(), e);
					}
				}
				if (c == '#' && (sb.length() > 1) && (sb.charAt(0) == '#')) {
					// #356896031498455,CMD-T,A,DATE:110107,TIME:061607,LAT:22.6474566N,LOT:114.0310116E,Speed:000.0,0-0-0-0-85-30,000#
					try {
						return parseThirdPartyCMD(sb);
					} catch (Exception e) {
						log.error(
								"parse command error for third party! "
										+ remoteAddr + "," + this.IMEI
										+ ",input:" + sb.toString(), e);
					}
				}
			}

		} catch (IOException e) {
			log.error(e);
			return new LostSignalCommand();
		}
		return null;
	}

	public Command readOneCommand3() {
		if (IMEI != null) { // it is the third party proctocal
			if (cmds.size() > 0) { // There is cmd left.
				return cmds.remove(0);
			}
		}
		ByteBuffer bf = ByteBuffer.allocate(1);
		StringBuffer sb = new StringBuffer();

		StringBuffer sb2 = new StringBuffer();
		try {
			int read = -1;
			String temp = "";
			while ((read = socketChannel.read(bf)) != -1) {// This method is not
				if (read == 0) {
					long time = System.currentTimeMillis();
					if (time - this.lastRecievedTime > this.lostSignalLimit) {
						return new LostSignalCommand();
					}
					return null;
				}
				char c = (char) bf.get(0);
				bf.clear();

				sb2.append(c);
				if (sb2.length() > 5
						&& sb2.substring(sb2.length() - 5, sb2.length()) == ",7428") {
					return parseCommandExt(sb.toString());

				} else {

					//
					if (c == '!') {
						sb.delete(0, sb.length());
					}
					// #356896031498455,CMD-T,A,DATE:110107,TIME:061607,LAT:22.6474566N,LOT:114.0310116E,Speed:000.0,0-0-0-0-85-30,000#
					if (c == '#' && (sb.length() > 1)
							&& ((sb.charAt(0) != '!') && (sb.charAt(0) != '#'))) {
						sb.delete(0, sb.length());
					}
					// System.out.println(remoteAddr+" input char:" + c);
					sb.append(c);
					lastRecievedTime = System.currentTimeMillis();
					if (c == ';') {
						try {
							return parseCommand(sb.toString());
						} catch (Exception e) {
							log.error(
									"parse command error! " + remoteAddr + ","
											+ this.IMEI + ",input:"
											+ sb.toString(), e);
						}
					}
					if (c == '#' && (sb.length() > 1) && (sb.charAt(0) == '#')) {
						// #356896031498455,CMD-T,A,DATE:110107,TIME:061607,LAT:22.6474566N,LOT:114.0310116E,Speed:000.0,0-0-0-0-85-30,000#
						try {
							return parseThirdPartyCMD(sb);
						} catch (Exception e) {
							log.error("parse command error for third party! "
									+ remoteAddr + "," + this.IMEI + ",input:"
									+ sb.toString(), e);
						}
					}
					//

				}

			}

		} catch (IOException e) {
			log.error(e);
			return new LostSignalCommand();
		}
		return null;
	}

	Integer flgInteger = 0;

	public Command readOneCommand2() {
		if (IMEI != null) { // it is the third party proctocal
			if (cmds.size() > 0) { // There is cmd left.
				return cmds.remove(0);
			}
		}
		ByteBuffer bf = ByteBuffer.allocate(1024);
		StringBuffer sb = new StringBuffer();
		try {
			int read = -1;

			// 读取信息获得读取的字节数
			bf.clear();
			while ((read = socketChannel.read(bf)) != -1) {
				if (read == 0) {
					long time = System.currentTimeMillis();
					if (time - this.lastRecievedTime > this.lostSignalLimit) {
						return new LostSignalCommand();
					}
					return null;
				}
				// 将缓冲区准备为数据传出状态
				bf.flip();
				// 将字节转化为为UTF-16的字符串
				String receivedString = Charset.forName("UTF-8").newDecoder()
						.decode(bf).toString();
				lastRecievedTime = System.currentTimeMillis();
				bf.clear();
				// 控制台打印出来
				// System.out.println("接收到来自"+socketChannel.socket().getRemoteSocketAddress()+"的信息:"
				// + receivedString);
				if (receivedString.length() > 0
						&& (receivedString.lastIndexOf(";") == receivedString
								.length() - 1)
						&& receivedString.indexOf("C,") < 0) {
					try {
						// System.out.println("1");
						return parseCommand(receivedString);
					} catch (Exception e) {
						log.error("parse command error! " + remoteAddr + ","
								+ this.IMEI + ",input:" + sb.toString(), e);
					}
				} else if (receivedString.indexOf(",GPRMC,") > 0) {
					try {
						// log.debug("new"+receivedString);
						/*
						 * if (flgInteger < 2) { // !1,012896003611529; String[]
						 * s = receivedString.split(","); flgInteger++; //
						 * System.out.println("2"); return parseCommand("!1," +
						 * s[16].replace("imei:", "")); } else {
						 * 
						 * }
						 */
						// System.out.println("3");
						return parseCommandExt(receivedString);// 自定义协议
					} catch (Exception e) {
						log.error("parse command error! " + remoteAddr + ","
								+ this.IMEI + ",input:" + sb.toString(), e);
					}
				} else if (receivedString.indexOf("C,") > 0) {
					try {
						// log.debug("new"+receivedString);
						/*
						 * if (flgInteger < 2) { // !1,012896003611529; String[]
						 * s = receivedString.split(","); flgInteger++; //
						 * System.out.println("2"); return parseCommand("!1," +
						 * s[16].replace("imei:", "")); } else {
						 * 
						 * }
						 */
						// System.out.println("3");
						return parseCommandExt_EV03(receivedString);// 自定义协议
					} catch (Exception e) {
						log.error("parse command error! " + remoteAddr + ","
								+ this.IMEI + ",input:" + sb.toString(), e);
					}
				}

				bf.clear();
			}

		} catch (IOException e) {
			log.error(e);
			return new LostSignalCommand();
		}

		return null;
	}

	/**
	 * #356896031498455,CMD-T,A,DATE:110107,TIME:061607,
	 * LAT:22.6474566N,LOT:114.0310116E,Speed:000.0, 0-0-0-0-85-30,000#
	 * 
	 * @param sb
	 * @throws ParseException
	 */
	private Command parseThirdPartyCMD(StringBuffer sb) throws ParseException {
		String line = sb.toString();

		// System.out.println("接收到信息--parseThirdPartyCMD"+line);

		log.debug(this.IMEI + ",Third party cmd:" + line);
		sb.delete(0, sb.length());
		line = line.replaceAll("[#]", "");
		String[] cmdsText = line.split(",");
		if (IMEI == null) {
			IMEI = cmdsText[0];
			GsnCommand cmd = new GsnCommand();
			cmd.setUserTrackerId(IMEI);
			cmds.add(cmd);
		}
		// ========== 不知道的协议, #27/01/11,14:32:37,12.884873,74.843262,0,0#
		if (cmdsText[0].indexOf("/") > -1) {
			return unknowData(cmdsText);
		}
		// ========== 不知道的协议
		// 非地理位置数据
		if (!cmdsText[1].equals(Command.THIRD_PARTY_CMD_T)) {
			parseThridPartyStatus(cmdsText);
		} else if ((trackerId != null)
				&& ParametersSetCache.getInstance().haveAction(trackerId,
						ActionType.THIRD_PARTY_ACTION_continuous_track)) { // 地理数据或者设置时间间隔事件
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}
		if (cmdsText.length < 3) {
			return cmds.remove(0); // 先返回第一条，可能是imei号
		}
		if (!cmdsText[2].equals("A")) { // gps信号没有修复好
			if (cmds.size() == 0)
				cmds.add(new HeartbreakCommand(2000l));
			return cmds.remove(0); // 先返回第一条，可能是imei号
		}
		DataCommand cmd = new DataCommand();
		String data = cmdsText[5];
		data = data.substring(4);
		cmd.setLatOrient(data.substring(data.length() - 1));
		cmd.setLat(Float.parseFloat(data.substring(0, data.length() - 1)));
		cmd.setOrig_lat(data);

		data = cmdsText[6];
		data = data.substring(4);
		cmd.setLngOrient(data.substring(data.length() - 1));
		cmd.setLng(Float.parseFloat(data.substring(0, data.length() - 1)));
		cmd.setOrig_lng(data);

		data = cmdsText[7];
		data = data.substring(6);
		cmd.setSpeed(Float.parseFloat(data));

		// System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag &
		// DataFlag.OVERSPEED)+"  data:"+data);
		cmd.setFlag(AlarmType.GPS_Pos.toString());

		data = cmdsText[3]; // DATE:110107
		data = data.substring(5);

		String d2 = cmdsText[4]; // TIME:061607
		d2 = d2.substring(5);
		Date date = ThreadSafeDateFormatter.parse2(data + " " + d2);
		if (!Tracker.PROTOCOL_TL201.equals(this.protocol)) // 201协议不加8
			date.setHours(date.getHours() + 8);
		cmd.setDate(date);

		String[] stats = cmdsText[8].split("-");
		if (stats.length <= 3) { // For TL201: In the format of XX-YY. XX means
									// the battery, the top is 100.YY means the
									// GSM signal, the top is 31.
			cmd.setBattery(new String(stats[0]));
			cmd.setGsm(new Integer(stats[1]));
		} else if (stats.length == 5) {
			/*
			 * For TL108: In the format of A-B-C-XX-YY. A=1 means ACC on, A=0
			 * means ACC off. B=1 means tracker get power for the car battery,
			 * B=0 means tracker lose power from car battery. C=1 means door
			 * open, C=0 means door close. XX means the battery, the top is 100.
			 * YY means the GSM signal, the top is 31.
			 */
			if (stats[0].equals("1")) {
				cmd.setAccStat(1);
			} else if (stats[0].equals("0")) {
				cmd.setAccStat(0);
			}
			if (stats[1].equals("0")) {
				cmd.setFlag(AlarmType.External_Power_Lost.name());
			}
			if (stats[2].equals("1")) {
				cmd.setDoorStat(1);
			} else if (stats[2].equals("0")) {
				cmd.setDoorStat(0);
			}
			cmd.setBattery(new String(stats[3]));
			cmd.setGsm(new Integer(stats[4]));
		} else if (stats.length == 6) {
			/*
			 * For TL108: In the format of X-X-X-X-BB-YY. BB means the battery,
			 * the top is 100. YY means the GSM signal, the top is 31.
			 */
			cmd.setBattery(new String(stats[4]));
			cmd.setGsm(new Integer(stats[5]));
		}
		if (cmdsText.length == 10 && cmdsText[9].length() > 0)
			cmd.setOrient(cmdsText[9]);
		else
			cmd.setOrient("0");

		cmds.add(cmd);

		return cmds.remove(0);
	}

	/**
	 * #356896031498455,CMD-T,A,DATE:110107,TIME:061607,
	 * LAT:22.6474566N,LOT:114.0310116E,Speed:000.0, 0-0-0-0-85-30,000#
	 * 
	 * @param cmdsText
	 * @return
	 */
	/**
	 * @param cmdsText
	 * @return
	 */
	private void parseThridPartyStatus(String[] cmdsText) {

		if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_X)) {
			cmds.add(new HeartbreakCommand(2000l));
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_A)) {
			ThirdPartySOSCommand cmd = new ThirdPartySOSCommand();
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_A1)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_A2)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_A3)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_A4)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_A5)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_ALM_B)) {
			ThirdPartyGEOCommand cmd = new ThirdPartyGEOCommand();
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_ALM_C)) {
			ThirdPartyOverSpeedCommand cmd = new ThirdPartyOverSpeedCommand();
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_ALM_D)) {
			ThirdPartyLowBatteryCommand cmd = new ThirdPartyLowBatteryCommand();
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_C)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_ERROR)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_F)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_H)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_I)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_J)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_L)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_N)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_O)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_T0)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_T1)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_U0)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_U1)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		} else if (cmdsText[1].equals(Command.THIRD_PARTY_CMD_M)) {
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}

	}

	/**
	 * #27/01/11,14:32:37,12.884873,74.843262,0,0#
	 * 
	 * @param cmdsText
	 * @return
	 * @throws ParseException
	 */
	private Command unknowData(String[] cmdsText) throws ParseException {
		DataCommand cmd = new DataCommand();
		String data = cmdsText[2];
		cmd.setLat(Float.parseFloat(data));
		cmd.setLatOrient(cmd.getLat() > 0 ? "N" : "S");
		cmd.setOrig_lat(data + cmd.getLatOrient());

		data = cmdsText[3];
		cmd.setLng(Float.parseFloat(data));
		cmd.setLngOrient(cmd.getLng() > 0 ? "E" : "W");
		cmd.setOrig_lng(data + cmd.getLngOrient());

		data = cmdsText[4];
		cmd.setSpeed(Float.parseFloat(data));

		data = cmdsText[0]; // 27/01/11
		String d2 = cmdsText[1]; // 14:32:37
		Date date = ThreadSafeDateFormatter.parse1(data + " " + d2);
		date.setHours(date.getHours() + 8);
		cmd.setDate(date);

		// System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag &
		// DataFlag.OVERSPEED)+"  data:"+data);
		data = cmdsText[5]; // flag

		// byte flag = HexString2Bytes(data)[0];

		if (data.equals(DataFlag.INPUT_1)) {
			cmd.setFlag(AlarmType.Input_1.toString());
		}
		if (data.equals(DataFlag.INPUT_2)) {
			cmd.setFlag(AlarmType.Input_2.toString());
		}
		if (data.equals(DataFlag.INPUT_3)) {
			cmd.setFlag(AlarmType.Input_3.toString());
		}
		if (data.equals(DataFlag.OVERSPEED)) {
			cmd.setFlag(AlarmType.Over_Speed_Alarm.toString());
		}
		if (data.equals(DataFlag.GEO)) {
			cmd.setFlag(AlarmType.Geo_Fence_Alarm.toString());
		}
		if (data.equals(DataFlag.EXT_POWER)) {
			cmd.setFlag(AlarmType.External_Power_Lost.toString());
		}
		if (data.equals(DataFlag.LOW_POWER_ALARM)) {
			cmd.setFlag(AlarmType.Low_Power_Alarm.toString());
		}
		if (data.equals(DataFlag.INPUT_4)) {
			cmd.setFlag(AlarmType.Input_4.toString());
		} else if (data.equals(DataFlag.INPUT_5)) {
			cmd.setFlag(AlarmType.Input_5.toString());
		} else if (data.equals(DataFlag.ACC_ON)) {
			cmd.setAccStat(1);
			cmd.setFlag(AlarmType.ACC_ON.toString());
		} else if (data.equals(DataFlag.ACC_OFF)) {
			cmd.setAccStat(0);
			cmd.setFlag(AlarmType.ACC_OFF.toString());
		} else if (data.equals(DataFlag.SIREN_ALARM)) {
			cmd.setFlag(AlarmType.SIREN.toString());
		} else if (data.equals(DataFlag.SOS)) {
			cmd.setFlag(AlarmType.SOS_Alarm.toString());
		} else if (data.equals(DataFlag.DOOR_OPENED)) {
			cmd.setDoorStat(1);
			cmd.setFlag(AlarmType.DOOR_OPENED.toString());
		} else if (data.equals(DataFlag.DOOR_CLOSED)) {
			cmd.setDoorStat(0);
			cmd.setFlag(AlarmType.DOOR_CLOSED.toString());
		}
		// System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag &
		// DataFlag.OVERSPEED)+"  data:"+data);
		if ((cmd.getFlag() == null)) {
			cmd.setFlag(AlarmType.GPS_Pos.toString());
		}

		return cmd;
	}

	private Command parseCommand(String sb) {
		try {
			String line = sb.trim();

			// System.out.println("接收到信息"+line);
			// sb.delete(0, sb.length());

			if (log.isDebugEnabled()) {
				log.debug(remoteAddr + "," + this.IMEI + ",parse command:"
						+ line);
			}
			line = line.replaceAll("[!;]", "");
			if (line.startsWith(Command.CMD_TYPE_MUTIL_DATA)) {
				line = line.substring(2);
				String[] cmdsText = line.split("#");
				// 多条数据：非固定（1-15条）
				/*
				 * !B,data1#data2#data3#data4#data5#data6#data7#data8#data9#data10
				 * #data11#data12#data13#data14#data15#; data1:
				 * date,time,lat,lot,speed,flag
				 */
				MutilDataCommand mutil = new MutilDataCommand();
				for (int i = 0; i < cmdsText.length; i++) {
					String l = cmdsText[i];
					String[] datas = l.split(",");
					mutil.addCmd(this.parseMutilData(datas));
				}
				return mutil;
			}

			String[] datas = line.split(",");

			if (datas[0].equals(Command.CMD_TYPE_GSN)) {
				GsnCommand cmd = new GsnCommand();
				cmd.setUserTrackerId(datas[1]);
				this.IMEI = datas[1];
				return cmd;
			} else if (datas[0].equals(Command.CMD_TYPE_DATA)) {

				DataCommand cmd = new DataCommand();
				String data = datas[1];
				cmd.setLatOrient(data.substring(data.length() - 1));
				cmd.setLat(Float.parseFloat(data.substring(0, data.length() - 1)));
				cmd.setOrig_lat(data);

				data = datas[2];
				cmd.setLngOrient(data.substring(data.length() - 1));
				cmd.setLng(Float.parseFloat(data.substring(0, data.length() - 1)));
				cmd.setOrig_lng(data);

				cmd.setSpeed(Float.parseFloat(datas[3]));

				data = datas[4]; // flag

				// byte flag = HexString2Bytes(data)[0];

				if (data.equals(DataFlag.INPUT_1)) {
					cmd.setFlag(AlarmType.Input_1.toString());
				}
				if (data.equals(DataFlag.INPUT_2)) {
					cmd.setFlag(AlarmType.Input_2.toString());
				}
				if (data.equals(DataFlag.INPUT_3)) {
					cmd.setFlag(AlarmType.Input_3.toString());
				}
				if (data.equals(DataFlag.OVERSPEED)) {
					cmd.setFlag(AlarmType.Over_Speed_Alarm.toString());
				}
				if (data.equals(DataFlag.GEO)) {
					cmd.setFlag(AlarmType.Geo_Fence_Alarm.toString());
				}
				if (data.equals(DataFlag.EXT_POWER)) {
					cmd.setFlag(AlarmType.External_Power_Lost.toString());
				}
				if (data.equals(DataFlag.LOW_POWER_ALARM)) {
					cmd.setFlag(AlarmType.Low_Power_Alarm.toString());
				}
				if (data.equals(DataFlag.INPUT_4)) {
					cmd.setFlag(AlarmType.Input_4.toString());
				} else if (data.equals(DataFlag.INPUT_5)) {
					cmd.setFlag(AlarmType.Input_5.toString());
				} else if (data.equals(DataFlag.ACC_ON)) {
					cmd.setAccStat(1);
					cmd.setFlag(AlarmType.ACC_ON.toString());
				} else if (data.equals(DataFlag.ACC_OFF)) {
					cmd.setAccStat(0);
					cmd.setFlag(AlarmType.ACC_OFF.toString());
				} else if (data.equals(DataFlag.SIREN_ALARM)) {
					cmd.setFlag(AlarmType.SIREN.toString());
				} else if (data.equals(DataFlag.SOS)) {
					cmd.setFlag(AlarmType.SOS_Alarm.toString());
				} else if (data.equals(DataFlag.DOOR_OPENED)) {
					cmd.setDoorStat(1);
					cmd.setFlag(AlarmType.DOOR_OPENED.toString());
				} else if (data.equals(DataFlag.DOOR_CLOSED)) {
					cmd.setDoorStat(0);
					cmd.setFlag(AlarmType.DOOR_CLOSED.toString());
				}
				// System.out.println("alarm type:" +
				// cmd.getFlag()+"  fl:"+(flag &
				// DataFlag.OVERSPEED)+"  data:"+data);
				if ((cmd.getFlag() == null)) {
					cmd.setFlag(AlarmType.GPS_Pos.toString());
				}

				return cmd;
			} else if (datas[0].equals(Command.CMD_TYPE_SINGLE_DATA)) {
				return parseSigleData(datas);
			} else if (datas[0].equals(Command.CMD_TYPE_CONFIG_STATUS)) {
				ConfigStatusCommand cmd = new ConfigStatusCommand();
				cmd.setStatus(datas[1]);
				return cmd;
			} else if (datas[0].equals(Command.CMD_TYPE_CONFIG_REQUEST_STATUS)) {
				ConfigRequestStatusCommand cmd = new ConfigRequestStatusCommand();
				String text = "";
				for (int i = 1; i < datas.length; i++) {
					text = text + datas[i] + ",";
				}
				text = text.substring(0, text.length() - 1);
				cmd.setStatus(text);
				return cmd;
			} else if (datas[0].equals(Command.CMD_TYPE_REQUEST_ADDRESS)) {
				RequestAddressCommand cmd = new RequestAddressCommand();
				cmd.setLat(datas[1]);
				cmd.setLng(datas[2]);
				return cmd;
			} else if (datas[0].equals(Command.CMD_TYPE_HEART_BREAK)) {
				return new HeartbreakCommand(1000);
			} else if (datas[0].equals(Command.CMD_TYPE_REQ_TRACKER_VERSION)) {
				ReqTrackerVerCommand cmd = new ReqTrackerVerCommand();
				cmd.setVersion(datas[1]);
				cmd.setCsq(datas[2]);
				return cmd;
			} else if (datas[0].equals(Command.CMD_TYPE_UPGRADE_FRAME_OK)) {
				UpgradeFrameStatusCommand cmd = new UpgradeFrameStatusCommand();
				cmd.setFrameAll(Integer.parseInt(datas[1], 16));
				cmd.setFrame(Integer.parseInt(datas[2], 16));
				cmd.setStatus(datas[3]);
				return cmd;
			} else if (datas[0].equals(Command.CMD_TYPE_UPGRADE_FRAME_ERROR)) {
				UpgradeFrameStatusCommand cmd = new UpgradeFrameStatusCommand();
				cmd.setFrameAll(Integer.parseInt(datas[1], 16));
				cmd.setFrame(Integer.parseInt(datas[2], 16));
				cmd.setStatus(datas[3]);
				return cmd;
			}
		} catch (Exception e) {
			log.error(e);
			return null;
		}

		return null;
	}

	private Command parseCommandExt(String sb) {
		try {
			String line = sb.trim();

			// System.out.println("接收到信息"+line);
			// sb.delete(0, sb.length());

			if (log.isDebugEnabled()) {
				log.debug(remoteAddr + "," + this.IMEI + ",parse command:"
						+ line);
			}

			// line = line.replaceAll("[!;]", "");
			String[] datas = line.split(",");
			return parseSigleDataExtNew(datas);

		} catch (Exception e) {
			log.error(e);
			return null;
		}
	}

	private Command parseCommandExt_EV03(String sb) {
		try {
			String line = sb.trim();
			// System.out.println("接收到信息"+line);
			// sb.delete(0, sb.length());
			if (log.isDebugEnabled()) {
				log.debug(remoteAddr + "," + this.IMEI + ",parse command:"
						+ line);
			}
			line = line.replaceAll("[!;]", "");
			String[] datas = line.split(",");
			if (datas[0].equals(Command.CMD_TYPE_GSN)) {
				GsnCommand cmd = new GsnCommand();
				cmd.setUserTrackerId(datas[1]);
				this.IMEI = datas[1];
				return cmd;
			} else {
				return parseSigleData_EV03(datas);
			}
		} catch (Exception e) {
			log.error(e);
			return null;
		}
	}

	private DataCommand parseMutilData(String[] datas) throws ParseException {
		/**
		 * 多条数据里的一条： date,time,lat,lot,speed,flag;
		 * 01/12/10,13:25:35,22.641724,114.023666,000.1,0; date：01/12/10 //日/月/年
		 * time：13:25:35 //时：分：秒 lat ：22.641724 //实数 lot ：114.023666 speed：000.1
		 * flag：0
		 */
		DataCommand cmd = new DataCommand();
		Date date = ThreadSafeDateFormatter.parse1(datas[0] + " " + datas[1]);
		date.setHours(date.getHours() + 8);
		cmd.setDate(date);

		cmd.setLat(Float.parseFloat(datas[2]));
		cmd.setOrig_lat(datas[2]);
		if (cmd.getLat() < 0) {
			cmd.setLatOrient("S");
			cmd.setLat(-cmd.getLat());
		} else {
			cmd.setLatOrient("N");
		}
		cmd.setLng(Float.parseFloat(datas[3]));
		cmd.setOrig_lng(datas[3]);
		if (cmd.getLng() < 0) {
			cmd.setLngOrient("W");
			cmd.setLng(-cmd.getLng());
		} else {
			cmd.setLngOrient("E");
		}

		cmd.setSpeed(Float.parseFloat(datas[4]));
		// cmd.setOrient(datas[6]);

		String data = datas[5]; // flag

		// byte flag = HexString2Bytes(data)[0];

		if (data.equals(DataFlag.INPUT_1)) {
			cmd.setFlag(AlarmType.Input_1.toString());
		}
		if (data.equals(DataFlag.INPUT_2)) {
			cmd.setFlag(AlarmType.Input_2.toString());
		}
		if (data.equals(DataFlag.INPUT_3)) {
			cmd.setFlag(AlarmType.Input_3.toString());
		}
		if (data.equals(DataFlag.OVERSPEED)) {
			cmd.setFlag(AlarmType.Over_Speed_Alarm.toString());
		}
		if (data.equals(DataFlag.GEO)) {
			cmd.setFlag(AlarmType.Geo_Fence_Alarm.toString());
		}
		if (data.equals(DataFlag.EXT_POWER)) {
			cmd.setFlag(AlarmType.External_Power_Lost.toString());
		}
		if (data.equals(DataFlag.LOW_POWER_ALARM)) {
			cmd.setFlag(AlarmType.Low_Power_Alarm.toString());
		}

		if (data.equals(DataFlag.INPUT_4)) {
			cmd.setFlag(AlarmType.Input_4.toString());
		} else if (data.equals(DataFlag.INPUT_5)) {
			cmd.setFlag(AlarmType.Input_5.toString());
		} else if (data.equals(DataFlag.ACC_ON)) {
			cmd.setAccStat(1);
			cmd.setFlag(AlarmType.ACC_ON.toString());
		} else if (data.equals(DataFlag.ACC_OFF)) {
			cmd.setAccStat(0);
			cmd.setFlag(AlarmType.ACC_OFF.toString());
		} else if (data.equals(DataFlag.SIREN_ALARM)) {
			cmd.setFlag(AlarmType.SIREN.toString());
		} else if (data.equals(DataFlag.SOS)) {
			cmd.setFlag(AlarmType.SOS_Alarm.toString());
		} else if (data.equals(DataFlag.DOOR_OPENED)) {
			cmd.setDoorStat(1);
			cmd.setFlag(AlarmType.DOOR_OPENED.toString());
		} else if (data.equals(DataFlag.DOOR_CLOSED)) {
			cmd.setDoorStat(0);
			cmd.setFlag(AlarmType.DOOR_CLOSED.toString());
		}

		// System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag &
		// DataFlag.OVERSPEED)+"  data:"+data);
		if ((cmd.getFlag() == null)) {
			cmd.setFlag(AlarmType.GPS_Pos.toString());
		}

		return cmd;
	}

	/**
	 * 单条数据： !A,date,time,lat,lot,speed,degrees,flag;
	 * !A,01/12/10,13:25:35,22.641724,114.023666,000.1,281.6,0; date：01/12/10
	 * //日/月/年 time：13:25:35 //时：分：秒 lat ：22.641724 //实数 lot ：114.023666
	 * speed：000.1 degrees：281.6 flag：0
	 * 
	 * @param datas
	 * @return
	 * @throws ParseException
	 */
	public static DataCommand parseSigleData(String[] datas)
			throws ParseException {

		DataCommand cmd = new DataCommand();
		Date date = ThreadSafeDateFormatter.parse1(datas[1] + " " + datas[2]);
		date.setHours(date.getHours() + 8);
		cmd.setDate(date);

		cmd.setLat(Float.parseFloat(datas[3]));
		cmd.setOrig_lat(datas[3]);
		if (cmd.getLat() < 0) {
			cmd.setLatOrient("S");
			cmd.setLat(-cmd.getLat());
		} else {
			cmd.setLatOrient("N");
		}
		cmd.setLng(Float.parseFloat(datas[4]));
		cmd.setOrig_lng(datas[4]);
		if (cmd.getLng() < 0) {
			cmd.setLngOrient("W");
			cmd.setLng(-cmd.getLng());
		} else {
			cmd.setLngOrient("E");
		}

		cmd.setSpeed(Float.parseFloat(datas[5]));
		cmd.setOrient(datas[6]);

		String data = datas[7]; // flag

		// byte flag = HexString2Bytes(data)[0];

		if (data.equals(DataFlag.INPUT_1)) {
			cmd.setFlag(AlarmType.Input_1.toString());
		}
		if (data.equals(DataFlag.INPUT_2)) {
			cmd.setFlag(AlarmType.Input_2.toString());
		}
		if (data.equals(DataFlag.INPUT_3)) {
			cmd.setFlag(AlarmType.Input_3.toString());
		}
		if (data.equals(DataFlag.OVERSPEED)) {
			cmd.setFlag(AlarmType.Over_Speed_Alarm.toString());
		}
		if (data.equals(DataFlag.GEO)) {
			cmd.setFlag(AlarmType.Geo_Fence_Alarm.toString());
		}
		if (data.equals(DataFlag.EXT_POWER)) {
			cmd.setFlag(AlarmType.External_Power_Lost.toString());
		}
		if (data.equals(DataFlag.LOW_POWER_ALARM)) {
			cmd.setFlag(AlarmType.Low_Power_Alarm.toString());
		}
		if (data.equals(DataFlag.INPUT_4)) {
			cmd.setFlag(AlarmType.Input_4.toString());
		} else if (data.equals(DataFlag.INPUT_5)) {
			cmd.setFlag(AlarmType.Input_5.toString());
		} else if (data.equals(DataFlag.ACC_ON)) {
			cmd.setAccStat(1);
			cmd.setFlag(AlarmType.ACC_ON.toString());
		} else if (data.equals(DataFlag.ACC_OFF)) {
			cmd.setAccStat(0);
			cmd.setFlag(AlarmType.ACC_OFF.toString());
		} else if (data.equals(DataFlag.SIREN_ALARM)) {
			cmd.setFlag(AlarmType.SIREN.toString());
		} else if (data.equals(DataFlag.SOS)) {
			cmd.setFlag(AlarmType.SOS_Alarm.toString());
		} else if (data.equals(DataFlag.DOOR_OPENED)) {
			cmd.setDoorStat(1);
			cmd.setFlag(AlarmType.DOOR_OPENED.toString());
		} else if (data.equals(DataFlag.DOOR_CLOSED)) {
			cmd.setDoorStat(0);
			cmd.setFlag(AlarmType.DOOR_CLOSED.toString());
		}
		// System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag &
		// DataFlag.OVERSPEED)+"  data:"+data);
		if ((cmd.getFlag() == null)) {
			cmd.setFlag(AlarmType.GPS_Pos.toString());
		}

		return cmd;
	}

	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"dd/MM/yy HH:mm:ss");

	public static Date parse1(String text) throws ParseException {
		synchronized (dateFormat) {
			return dateFormat.parse(text);
		}
	}

	/**
	 * 阿拉伯新加协议例如：0808251603,13145826127,GPRMC,160321.000,A,2234.0218,N,
	 * 11403.0737
	 * ,E,0.00,,250808,,,A*78,F,imei:359586019278139,05,135.2,F:4.32V,0,136,
	 * 46672, 460,01,2533,7428
	 * 
	 * @param datas
	 * @return
	 * @throws ParseException
	 */
	public DataCommandXuXun parseSigleDataExtNew(String[] datas)
			throws ParseException {

		DataCommandXuXun cmd = new DataCommandXuXun();
		/*
		 * GsnCommand cmd = new GsnCommand(); cmd.setUserTrackerId(datas[1]);
		 * this.IMEI = datas[1]; return cmd;
		 */

		String imie = datas[17].replace("imei:", "").trim();
		cmd.setUserTrackerId(imie);
		this.IMEI = imie;

		String dateString = datas[11];
		String timeString = datas[3].substring(0, 6);
		Date date = dateFormat.parse(dateString.substring(0, 2) + "/"
				+ dateString.substring(2, 4) + "/20"
				+ dateString.substring(4, 6) + " " + timeString.substring(0, 2)
				+ ":" + timeString.substring(2, 4) + ":"
				+ timeString.substring(4, 6));

		date.setHours(date.getHours() + 8);
		cmd.setDate(date);
		String latString = String.valueOf(Float.parseFloat(datas[5]) / 100);

		Float latString2 = Float.parseFloat(latString.substring(0,
				latString.indexOf(".")));

		Float latString3 = (Float.parseFloat("0"
				+ latString.substring(latString.indexOf("."),
						latString.length())) * 100) / 60;

		cmd.setLat(Float.parseFloat(String.valueOf(latString2 + latString3)));// 经度
		cmd.setOrig_lat(datas[5]);
		if (cmd.getLat() < 0) {
			cmd.setLatOrient("S");
			cmd.setLat(-cmd.getLat());
		} else {
			cmd.setLatOrient("N");
		}

		String orgString = String.valueOf(Float.parseFloat(datas[7]) / 100);
		Float orgString2 = Float.parseFloat(orgString.substring(0,
				orgString.indexOf(".")));

		Float orgString3 = (Float.parseFloat("0"
				+ orgString.substring(orgString.indexOf("."),
						orgString.length())) * 100) / 60;

		// cmd.setLat(Float.parseFloat(String.valueOf(orgString2+orgString3)));//经度

		cmd.setLng(Float.parseFloat(String.valueOf(orgString2 + orgString3)));// 维度
		cmd.setOrig_lng(datas[7]);
		if (cmd.getLng() < 0) {
			cmd.setLngOrient("W");
			cmd.setLng(-cmd.getLng());
		} else {
			cmd.setLngOrient("E");
		}
		cmd.setSpeed(Float.parseFloat(datas[9]));
		cmd.setOrient(datas[10]);// 方向

		cmd.setFlag("GPS_Pos");

		// String data = datas[7]; // flag 报警标示

		// byte flag = HexString2Bytes(data)[0];
		// alarm process ;
		/*
		 * if (data.equals(DataFlag.INPUT_1)) {
		 * cmd.setFlag(AlarmType.Input_1.toString()); } if
		 * (data.equals(DataFlag.INPUT_2)) {
		 * cmd.setFlag(AlarmType.Input_2.toString()); } if
		 * (data.equals(DataFlag.INPUT_3)) {
		 * cmd.setFlag(AlarmType.Input_3.toString()); } if
		 * (data.equals(DataFlag.OVERSPEED)) {
		 * cmd.setFlag(AlarmType.Over_Speed_Alarm.toString()); } if
		 * (data.equals(DataFlag.GEO)) {
		 * cmd.setFlag(AlarmType.Geo_Fence_Alarm.toString()); } if
		 * (data.equals(DataFlag.EXT_POWER)) {
		 * cmd.setFlag(AlarmType.External_Power_Lost.toString()); } if
		 * (data.equals(DataFlag.LOW_POWER_ALARM)) {
		 * cmd.setFlag(AlarmType.Low_Power_Alarm.toString()); } if
		 * (data.equals(DataFlag.INPUT_4)) {
		 * cmd.setFlag(AlarmType.Input_4.toString()); } else if
		 * (data.equals(DataFlag.INPUT_5)) {
		 * cmd.setFlag(AlarmType.Input_5.toString()); } else if
		 * (data.equals(DataFlag.ACC_ON)) { cmd.setAccStat(1);
		 * cmd.setFlag(AlarmType.ACC_ON.toString()); } else if
		 * (data.equals(DataFlag.ACC_OFF)) { cmd.setAccStat(0);
		 * cmd.setFlag(AlarmType.ACC_OFF.toString()); } else if
		 * (data.equals(DataFlag.SIREN_ALARM)) {
		 * cmd.setFlag(AlarmType.SIREN.toString()); } else if
		 * (data.equals(DataFlag.SOS)) {
		 * cmd.setFlag(AlarmType.SOS_Alarm.toString()); } else if
		 * (data.equals(DataFlag.DOOR_OPENED)) { cmd.setDoorStat(1);
		 * cmd.setFlag(AlarmType.DOOR_OPENED.toString()); } else if
		 * (data.equals(DataFlag.DOOR_CLOSED)) { cmd.setDoorStat(0);
		 * cmd.setFlag(AlarmType.DOOR_CLOSED.toString()); } //
		 * System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag & //
		 * DataFlag.OVERSPEED)+"  data:"+data); if ((cmd.getFlag() == null)) {
		 * cmd.setFlag(AlarmType.GPS_Pos.toString()); }
		 */

		return cmd;

	}

	public DataCommandXuXun parseSigleDataExtNew_EV03(String[] datas)
			throws ParseException {
		DataCommandXuXun cmd = new DataCommandXuXun();
		/*
		 * GsnCommand cmd = new GsnCommand(); cmd.setUserTrackerId(datas[1]);
		 * this.IMEI = datas[1]; return cmd;
		 */
		String imie = datas[17].replace("imei:", "").trim();
		cmd.setUserTrackerId(imie);
		this.IMEI = imie;

		String dateString = datas[11];
		String timeString = datas[3].substring(0, 6);
		Date date = dateFormat.parse(dateString.substring(0, 2) + "/"
				+ dateString.substring(2, 4) + "/20"
				+ dateString.substring(4, 6) + " " + timeString.substring(0, 2)
				+ ":" + timeString.substring(2, 4) + ":"
				+ timeString.substring(4, 6));

		date.setHours(date.getHours() + 8);
		cmd.setDate(date);
		String latString = String.valueOf(Float.parseFloat(datas[5]) / 100);

		Float latString2 = Float.parseFloat(latString.substring(0,
				latString.indexOf(".")));

		Float latString3 = (Float.parseFloat("0"
				+ latString.substring(latString.indexOf("."),
						latString.length())) * 100) / 60;

		cmd.setLat(Float.parseFloat(String.valueOf(latString2 + latString3)));// 经度

		cmd.setOrig_lat(datas[5]);
		if (cmd.getLat() < 0) {
			cmd.setLatOrient("S");
			cmd.setLat(-cmd.getLat());
		} else {
			cmd.setLatOrient("N");
		}

		String orgString = String.valueOf(Float.parseFloat(datas[7]) / 100);

		Float orgString2 = Float.parseFloat(orgString.substring(0,
				orgString.indexOf(".")));

		Float orgString3 = (Float.parseFloat("0"
				+ orgString.substring(orgString.indexOf("."),
						orgString.length())) * 100) / 60;

		// cmd.setLat(Float.parseFloat(String.valueOf(orgString2+orgString3)));//经度

		cmd.setLng(Float.parseFloat(String.valueOf(orgString2 + orgString3)));// 维度
		cmd.setOrig_lng(datas[7]);
		if (cmd.getLng() < 0) {
			cmd.setLngOrient("W");
			cmd.setLng(-cmd.getLng());
		} else {
			cmd.setLngOrient("E");
		}
		cmd.setSpeed(Float.parseFloat(datas[9]));
		cmd.setOrient(datas[10]);// 方向

		cmd.setFlag("GPS_Pos");

		// String data = datas[7]; // flag 报警标示

		// byte flag = HexString2Bytes(data)[0];
		// alarm process ;
		/*
		 * if (data.equals(DataFlag.INPUT_1)) {
		 * cmd.setFlag(AlarmType.Input_1.toString()); } if
		 * (data.equals(DataFlag.INPUT_2)) {
		 * cmd.setFlag(AlarmType.Input_2.toString()); } if
		 * (data.equals(DataFlag.INPUT_3)) {
		 * cmd.setFlag(AlarmType.Input_3.toString()); } if
		 * (data.equals(DataFlag.OVERSPEED)) {
		 * cmd.setFlag(AlarmType.Over_Speed_Alarm.toString()); } if
		 * (data.equals(DataFlag.GEO)) {
		 * cmd.setFlag(AlarmType.Geo_Fence_Alarm.toString()); } if
		 * (data.equals(DataFlag.EXT_POWER)) {
		 * cmd.setFlag(AlarmType.External_Power_Lost.toString()); } if
		 * (data.equals(DataFlag.LOW_POWER_ALARM)) {
		 * cmd.setFlag(AlarmType.Low_Power_Alarm.toString()); } if
		 * (data.equals(DataFlag.INPUT_4)) {
		 * cmd.setFlag(AlarmType.Input_4.toString()); } else if
		 * (data.equals(DataFlag.INPUT_5)) {
		 * cmd.setFlag(AlarmType.Input_5.toString()); } else if
		 * (data.equals(DataFlag.ACC_ON)) { cmd.setAccStat(1);
		 * cmd.setFlag(AlarmType.ACC_ON.toString()); } else if
		 * (data.equals(DataFlag.ACC_OFF)) { cmd.setAccStat(0);
		 * cmd.setFlag(AlarmType.ACC_OFF.toString()); } else if
		 * (data.equals(DataFlag.SIREN_ALARM)) {
		 * cmd.setFlag(AlarmType.SIREN.toString()); } else if
		 * (data.equals(DataFlag.SOS)) {
		 * cmd.setFlag(AlarmType.SOS_Alarm.toString()); } else if
		 * (data.equals(DataFlag.DOOR_OPENED)) { cmd.setDoorStat(1);
		 * cmd.setFlag(AlarmType.DOOR_OPENED.toString()); } else if
		 * (data.equals(DataFlag.DOOR_CLOSED)) { cmd.setDoorStat(0);
		 * cmd.setFlag(AlarmType.DOOR_CLOSED.toString()); } //
		 * System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag & //
		 * DataFlag.OVERSPEED)+"  data:"+data); if ((cmd.getFlag() == null)) {
		 * cmd.setFlag(AlarmType.GPS_Pos.toString()); }
		 */

		return cmd;

	}

	public static DataCommand parseSigleData_EV03(String[] datas)
			throws ParseException {

		DataCommand cmd = new DataCommand();
		Date date = ThreadSafeDateFormatter.parse1(datas[1] + " " + datas[2]);
		date.setHours(date.getHours() + 8);
		cmd.setDate(date);

		cmd.setLat(Float.parseFloat(datas[3]));
		cmd.setOrig_lat(datas[3]);
		if (cmd.getLat() < 0) {
			cmd.setLatOrient("S");
			cmd.setLat(-cmd.getLat());
		} else {
			cmd.setLatOrient("N");
		}
		cmd.setLng(Float.parseFloat(datas[4]));
		cmd.setOrig_lng(datas[4]);
		if (cmd.getLng() < 0) {
			cmd.setLngOrient("W");
			cmd.setLng(-cmd.getLng());
		} else {
			cmd.setLngOrient("E");
		}
		cmd.setSpeed(Float.parseFloat(datas[5]));
		cmd.setOrient(datas[6]);
		String data = datas[7]; // flag
		
		// byte flag = HexString2Bytes(data)[0];
		Integer flags=Integer.valueOf(data,16);
		
//		String gpsmodeString="";
//		 Integer c=(flags>>2);
//		 Integer ac=flags>>0x03;
//		cmd.setFlag((flags).toString());
		//cmd.setTemp(flags.toString());
		cmd.setTemp(data);
		
		cmd.setTemp3(flags);
		
		//System.out.println(flags);
		if (data.equals(DataFlag.INPUT_1)) {
			cmd.setFlag(AlarmType.Input_1.toString());
		}
		if (data.equals(DataFlag.INPUT_2)) {
			cmd.setFlag(AlarmType.Input_2.toString());
		}
		if (data.equals(DataFlag.INPUT_3)) {
			cmd.setFlag(AlarmType.Input_3.toString());
		}
		if (data.equals(DataFlag.OVERSPEED)) {
			cmd.setFlag(AlarmType.Over_Speed_Alarm.toString());
		}
		if (data.equals(DataFlag.GEO)) {
			cmd.setFlag(AlarmType.Geo_Fence_Alarm.toString());
		}
		if (data.equals(DataFlag.EXT_POWER)) {
			cmd.setFlag(AlarmType.External_Power_Lost.toString());
		}
		if (data.equals(DataFlag.LOW_POWER_ALARM)) {
			cmd.setFlag(AlarmType.Low_Power_Alarm.toString());
		}
		if (data.equals(DataFlag.INPUT_4)) {
			cmd.setFlag(AlarmType.Input_4.toString());
		} else if (data.equals(DataFlag.INPUT_5)) {
			cmd.setFlag(AlarmType.Input_5.toString());
		} else if (data.equals(DataFlag.ACC_ON)) {
			cmd.setAccStat(1);
			cmd.setFlag(AlarmType.ACC_ON.toString());
		} else if (data.equals(DataFlag.ACC_OFF)) {
			cmd.setAccStat(0);
			cmd.setFlag(AlarmType.ACC_OFF.toString());
		} else if (data.equals(DataFlag.SIREN_ALARM)) {
			cmd.setFlag(AlarmType.SIREN.toString());
		} else if (data.equals(DataFlag.SOS)) {
			cmd.setFlag(AlarmType.SOS_Alarm.toString());
		} else if (data.equals(DataFlag.DOOR_OPENED)) {
			cmd.setDoorStat(1);
			cmd.setFlag(AlarmType.DOOR_OPENED.toString());
		} else if (data.equals(DataFlag.DOOR_CLOSED)) {
			cmd.setDoorStat(0);
			cmd.setFlag(AlarmType.DOOR_CLOSED.toString());
		}
		// System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag &
		// DataFlag.OVERSPEED)+"  data:"+data);
		if ((cmd.getFlag() == null)) {
			cmd.setFlag(AlarmType.GPS_Pos.toString());
		}
		
		cmd.setVoltage(datas[8]);
		cmd.setBattery(datas[9]);
		cmd.setFuel(datas[10]);
		cmd.setAd2(datas[11]);
		return cmd;
	}

	// 转化字符串为十六进制编码
	public static String toHexString(String s) {
		String str = "";
		for (int i = 0; i < s.length(); i++) {
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch);
			str = str + s4;
		}
		return str;
	}

	// 转化十六进制编码为字符串
	public static String toStringHex1(String s) {
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(
						s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			s = new String(baKeyword, "utf-8");// UTF-16le:Not
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	}

	// 转化十六进制编码为字符串
	public static String toStringHex2(String s) {
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(
						s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			s = new String(baKeyword, "utf-8");// UTF-16le:Not
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	}

	public byte uniteBytes(byte src0, byte src1) {
		byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
				.byteValue();
		_b0 = (byte) (_b0 << 4);
		byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
				.byteValue();
		byte ret = (byte) (_b0 ^ _b1);
		return ret;
	}

	/**
	 * 将指定字符串src，以每两个字符分割转换为16进制形式 如："2B44EFD9" --> byte[]{0x2B, 0x44, 0xEF,
	 * 0xD9}
	 * 
	 * @param src
	 *            String
	 * @return byte[]
	 */
	public byte[] HexString2Bytes(String src) {
		byte[] ret = new byte[1];
		byte[] tmp = src.getBytes();
		for (int i = 0; i < 1; i++) {
			ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
		}
		return ret;
	}

}
